﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using WebSocketCore.Domain.Account;
using WebSocketCore.Domain.Cfg;
using WebSocketCore.Domain.Entities;

namespace WebSocketCore.Domain.Impl
{
    public class ChatRoomManager : IChatRoomManager
    {
        protected IMessageManager _messageManager;
        public ChatRoomManager(IMessageManager messageManager)
        {
            
            this._messageManager = messageManager;
        }
        //TODO Db
        protected IList<ChatRoomEntity> rooms { get { return DbInit.RoomsInit; } }
        public void AddRoom(ChatRoomEntity chatRoomEntity)
        {
            rooms.Add(chatRoomEntity);
        }
        public IEnumerable<Tuple<string, string>> GetRooms()
        {
            return rooms.Select(m => new Tuple<string, string>(m.Id, m.ChatRoomName));
        }
        public string GetRoomName(string id)
        {
            return rooms.First(m => m.Id == id).ChatRoomName;
        }
        public ChatRoomEntity GetUserRoom(IUser user)
        {
            foreach (var item in rooms)
            {
                if(item.WebSockets.Any(n => n.User.Id == user.Id))
                {
                    return item;
                }
            }
            return null;
            //return rooms.FirstOrDefault(m => m.WebSockets.Any(n => n.User == user));
        }
        public async Task AddUserToRoom(string roomId, IUser user, WebSocket webSocket)
        {
            ChatRoomEntity oldRoom = GetUserRoom(user);
            if (oldRoom != null)
            {
                if (oldRoom.Id == roomId)//重复进入同一个聊天室
                {
                    //if (oldRoom[user].State != WebSocketState.Open)//断线重连 不能这样访问，异常
                    //{
                        //await oldRoom[user].CloseAsync( WebSocketCloseStatus.NormalClosure,"已在其他地方登陆",CancellationToken.None);
                        //oldRoom[user] = webSocket;
                       // await RemoveUserFromRoom(oldRoom, user);
                    //}
                    //else//重复进入
                    //{
                        //await RemoveUserFromRoom(oldRoom, user, webSocket);
                    //}
                    await RemoveUserFromRoom(oldRoom, user, webSocket, false);
                }
                else//切换聊天室
                {
                    await RemoveUserFromRoom(oldRoom, user, webSocket,false);
                }
            }
            await rooms.First(m => m.Id == roomId).AddUser(user, webSocket);
        }
        public async Task RemoveUserFromRoom(ChatRoomEntity room, IUser user,WebSocket webSocket,bool dispose=true)
        {
            await room.RemoveUser(user, webSocket,dispose);
        }
        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="roomId"></param>
        ///// <param name="user"></param>
        ///// <returns>0：不在房间 1：切换房间 2:已经在此房间</returns>
        //public int CheckUserInRoom(string roomId, IUser user)
        //{
        //    if (rooms.Any(m => m.WebSockets.Any(n => n.User == user)))
        //    {
        //        var room = rooms.First(m => m.WebSockets.Any(n => n.User == user));
        //        if (room.Id == roomId)
        //        {
        //            return 2;//已经在此房间
        //        }
        //        return 1;//切换房间
        //    }
        //    return 0;//不在房间
        //}
        public bool HasRoom(string roomId)
        {
            return rooms.Any(m => m.Id == roomId);
        }

        public async Task NotifyAllAsync(MessageEntity msg)
        {
            foreach (var item in rooms)
            {
                await item.NotifyAsync(msg);
            }
        }

        public async Task NotifyRoomAsync(string roomId, MessageEntity msg)
        {
            await rooms.First(m => m.Id == roomId).NotifyAsync(msg);
        }


    }
}
